﻿<template>

  <el-row class="container">

    <!--头部-->

    <el-col v-if="showTop"
            :span="24">

      <router-view name="top"></router-view>

    </el-col>

    <el-col :span="24"
            :style="{height:showTop?'calc(100vh - 65px)':'100vh',top:showTop?'65px':'0'}"
            class="main">

      <!--左侧导航-->

      <router-view v-if="showLeft"
                   name="aside"></router-view>

      <!--右侧内容区-->

      <section class="content-container">

        <router-view v-if="showLeft"
                     name="activeTabs"></router-view>

        <div id="micro-container"
             class="grid-content bg-purple-light">

          <transition name="fade"
                      mode="out-in">
            <keep-alive :include="alivePageList">
              <router-view></router-view>
            </keep-alive>
          </transition>

          <!-- 智慧工地评价系统 -->

          <div id="eva-container"></div>

          <div id="vue-container"></div>

          <div id="hammer-container"></div>

          <div id="ass-container"></div>

          <div id="intecons-container"></div>

          <div id="storeMicro-container"></div>

          <div id="score-container"></div>

          <div id="conlabor-container"></div>

        </div>

        <div id="consult-container"></div>

      </section>

    </el-col>
    <!-- 工单系统入口 -->
    <div class="report-content"
         @click="openDrawer"
         title="工单反馈">
      <i class="el-icon-edit-outline"></i>
    </div>
    <el-drawer title="工单反馈"
               :visible.sync="drawerVisible">
      <iframe :src="reportUrl"
              width="100%"
              height="100%"
              frameborder="0"></iframe>
    </el-drawer>

    <img @click="showProjectList"
         class="project-icon"
         v-if="showProjectImg"
         src="/static/img/xiangmu.gif"
         alt="" />

    <EditUserInfoDialog :dialogVisible.sync="userInfoDialogVisible"></EditUserInfoDialog>

    <ProjectListDialog :dialogVisible.sync="projectListDialogVisible"></ProjectListDialog>

    <NewMap :latlng.sync="latlng"
            :dialogVisible.sync="mapDialogVisible"></NewMap>

  </el-row>

</template>

<script>

// import { userInfoApi } from '@/services/user'

import { userPermissionApi } from "@/services/UserPermission";

import { ProjectListApi } from "@/services/ProjectCenter";

import EditUserInfoDialog from "@/components/EditUserInfo/EditUserInfoDialog";

import ProjectListDialog from "@/components/ProjectList/ProjectListDialog";

import { initGlobalState } from "qiankun";

import NewMap from "@/components/Map/NewMap";

export default {

  name: "home",

  data () {

    return {
      alivePageList: ['platFormProjectList', 'activeManagement', 'platPeopleWarehousePage'],

      showProjectImg: true,

      loading: false,

      requestParams: {

        id: 1

      },

      userMenu: [],

      // 完善用户资料弹框是否可见

      editUserInfoDialogVisible: false,

      // 项目列表弹框是否可见

      projectListDialogVisible: false,

      // 项目列表请求参数

      requestParam: {
        province_no: "",
        city_no: "",
        area_no: "",
        company_id: "",
        project_name: "",
        page: 1,
        per_page: 10000000
      },

      // 地图弹框是否可见

      mapDialogVisible: false,

      latlng: {

        lng: "",

        lat: ""

      },
      showTop: true,
      showLeft: true,
      // 工单反馈抽屉是否可见
      drawerVisible: false,
      // 工单反馈页面url
      reportUrl: ''
    };

  },

  components: {

    EditUserInfoDialog,

    ProjectListDialog,

    NewMap

  },

  computed: {

    userInfoDialogVisible () {

      let store = this.$store.state.userInfoDialogVisible;

      return store;

    },

    chooseLatDialogVisible () {

      let store = this.$store.state.chooseLatDialogVisible;

      return store;

    }

  },

  watch: {
    chooseLatDialogVisible: {
      handler (newval) {
        this.mapDialogVisible = newval;
      },
      deep: true
    },
    latlng: {
      handler (newval) {
        if (newval.lat) {
          this.$pager.next({
            action: "latlngData",
            data: newval
          });
        }
      },
      deep: true
    },
    '$store.state.showTop': {
      handler (newval) {
        this.showTop = newval
      },
      immediate: true
    },
    '$store.state.showLeft': {
      handler (newval) {
        this.showLeft = newval
      },
      immediate: true
    }
  },
  methods: {
    openDrawer () {
      this.drawerVisible = true
      let userInfo = window.localStorage.getItem('userInfo') || '{}'
      userInfo = JSON.parse(userInfo)
      let systemName = '智慧工地'
      let userName = userInfo.user_name
      let pn = userInfo.phone
      let userId = userInfo.user_id
      let scene = 'portal'
      let token = userInfo.access_token
      this.reportUrl = `https://slave-feedback.hibuilding.cn/slave-feedback/list?systemName=${systemName}&userName=${userName}&pn=${pn}&userId=${userId}&scene=${scene}&token=${token}`
    },
    // 显示项目列表弹框
    showProjectList () {
      this.projectListDialogVisible = true;
    },
    setUserMenu () {
      let roleInfo = {
        nav: {},
        topNav: []
      };
      this.$store.dispatch("addRole", roleInfo);
      let first = "";
      this.userMenu.map(item => {
        roleInfo.nav[item.menu_id] = item.children_list;
        roleInfo.topNav.push(item);
      });
      first = roleInfo.topNav[0].menu_id;
      window.localStorage.setItem("platFormRoleInfo", JSON.stringify(roleInfo));
      if (
        window.localStorage.getItem("platFormSideNav") === "undefined" ||
        window.localStorage.getItem("platFormSideNav") === null
      ) {
        this.$store.dispatch("sideNav", roleInfo.nav[first]);
        window.localStorage.setItem(
          "platFormSideNav",
          JSON.stringify(roleInfo.nav[first])
        );

      }

    },

    getKey () {

      userPermissionApi

        .getKey({

          data: {

            system_no: "industry",

            auth_code: "CED4DE04-BA74-81DF-E51E-9864E4FD0DCB"

          }

        })

        .then(

          res => { },

          err => {

            console.log(err);

          }

        );

    },

    login () {

      userPermissionApi.login({

        data: {

          user_no: "18200283200",

          password: "hz123456",

          login_type: "1"

        }

      });

    },

    // 获取菜单

    getMenuTree () {
      let userId = window.localStorage.getItem("user_id");
      // 判断是否已请求过菜单
      let local = window.localStorage.getItem('platFormRoleInfo')
      if (local) {
        let roleInfo = JSON.parse(local)
        let first = roleInfo.topNav[0].menu_id;
        this.$store.dispatch("addRole", roleInfo);
        this.$store.dispatch("sideNav", roleInfo.nav[first]);
        window.localStorage.setItem(
          "platFormSideNav",
          JSON.stringify(roleInfo.nav[first])
        );
      } else {
        userPermissionApi.getMenuTree({
          data: {
            user_id: userId
          }
        }).then(res => {
          let map = new Map();
          // 所有用户都要显示5个中心加首页，所以写死5个中心的菜单编号，与接口数据对比，没有就设置空数组
          let menuNoList = [
            { no: "project_center", name: "项目中心" },
            { no: "work-center", name: "工作中心" },
            { no: "personal-center", name: "个人中心" },
            { no: "resource-center", name: "资源中心" },
            { no: "config-center", name: "配置中心" },
            // { no: "work-bench", name: "工作台" }
          ];
          let menuList = [];
          if (res.data.list.length > 0) {
            // 以菜单编号为key，存入map
            res.data.list.map(item => {
              map.set(item.menu_no, item);
            });
            // 手动添加首页
            // menuList.push({
            //   menu_id: 'home_page',
            //   menu_name: '首页',
            //   route_url: 'homepage',
            //   menu_type: '1'
            // })
            // 遍历写死的菜单列表，与接口数据对比，有数据的以接口数据为准，没有的模拟一个对象
            menuNoList.map(menuNo => {
              let val = map.get(menuNo.no);
              if (val !== undefined) {
                menuList.push(val);
              } else {
                menuList.push({
                  menu_id: menuNo.no,
                  menu_name: menuNo.name,
                  children_list: []
                });
              }
            });
            // this.userMenu = res.data.list;
            this.userMenu = menuList;
            // this.$store.dispatch('setUserMenu', this.userMenu)
            this.setUserMenu();
          }
        });
      }

    },
    // 获取项目列表
    getProjectList () {
      ProjectListApi.getProjectList({
        params: this.requestParam
      }).then(
        res => {
          if (res.code === 0) {
            localStorage.setItem(
              "AllProjectList",
              JSON.stringify(res.data.list)
            );
            // 判断是否已选择了项目，已选择不处理，未选择默认取第一个
            let storage = window.localStorage.getItem("choosedProject") || "{}";
            let choosedProject = JSON.parse(storage);
            choosedProject = choosedProject.project_id
              ? choosedProject
              : res.data.list[0];
            this.$store.dispatch("setProject", choosedProject);
            this.$store.dispatch("setProjectIdList", [
              choosedProject.project_id
            ]);
            let state = {
              projectList: {
                list: []
              },
              choosedProject: {}
            };
            state.choosedProject = choosedProject.project_id
              ? choosedProject : res.data.list[0];
            state.projectList.list = res.data.list || [];
            const actions = initGlobalState(state);
            actions.setGlobalState(state);
          }
        },
        err => {
          console.log(err);
        }

      );

    }

  },

  mounted () {

    let companyInfo = window.localStorage.getItem("companyInfo") || "{}";

    companyInfo = JSON.parse(companyInfo);

    // 设置页面title为接口返回的数据

    let title = document.getElementsByTagName("title");

    title[0].innerText = companyInfo.platform_name || companyInfo.company_name;

    // 如果设置了公司logo，就将浏览器标签页的icon修改为logo

    if (companyInfo.company_logo) {

      let logo = document.querySelector(".tab-icon");

      logo.href = companyInfo.company_logo;

    }

    //判断是否有token

    // if (window.sessionStorage.getItem("access_token")) {
    //   this.getMenuTree();
    //   this.getProjectList();
    // }
    let accessToken = window.localStorage.getItem("access_token");
    let isZLJ = window.localStorage.getItem('zlj')
    if (accessToken) {
      window.sessionStorage.setItem('access_token', accessToken)
      this.getMenuTree();
      this.getProjectList();
    } else {
      // 当在浙里建使用时，不跳转登陆页
      if (isZLJ !== '1') {
        this.$router.push({
          path: "/login"
        });
      }

    }
    this.showProjectImg = window.location.pathname !== "/checkResultDetail";
  },

  created () { }

};

</script>

<style lang="scss" scoped>
.main {
  min-height: 500px;

  height: calc(100vh - 65px);

  overflow-y: auto;
}
.report-content {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #3a73fd;
  position: absolute;
  bottom: 24px;
  right: 24px;
  z-index: 11;
  font-size: 24px;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}
/deep/ .left_nav {
  width: auto;

  height: 100vh;

  border-right: solid 1px #e6e6e6;

  overflow-y: auto;
}

.container {
  .project-icon {
    width: 52px;

    height: 60px;

    position: fixed;

    top: 30%;

    right: 0;

    cursor: pointer;

    z-index: 999;
  }
}
</style>